package com.atjyb.auth.service.Impl;

import com.atjyb.auth.mapper.SysRoleMapper;
import com.atjyb.auth.mapper.SysUserMapper;
import com.atjyb.auth.service.SysRoleService;
import com.atjyb.auth.service.SysUserRoleService;
import com.atjyb.auth.service.SysUserService;
import com.atjyb.common.result.Result;
import com.atjyb.model.system.SysRole;
import com.atjyb.model.system.SysUserRole;
import com.atjyb.vo.system.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Override
    public Map<String, Object> findRoleByAdminId(Long userId) {
        //获取所有角色
        List<SysRole> allRoles = baseMapper.selectList(null);

        //获取目标用户的在SysUserRole中的所有角色(id)
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq( SysUserRole::getUserId,userId);
        List<SysUserRole> existUserRoleList = sysUserRoleService.list(wrapper);

       //获取所有角色（得到角色id集合）
        List<Long> existRoleList
                = existUserRoleList.stream().map(c -> c.getRoleId()).collect(Collectors.toList());

        //根据角色id集合查询角色的具体信息
        List<SysRole> roleList =new ArrayList<>();
        for (SysRole role : allRoles) {
            if (existRoleList.contains(role.getId())){
                roleList.add(role);
            }
        }

        Map<String,Object> map=new HashMap<>();
        map.put("assignedRoleList",roleList);
        map.put("allRolesList",allRoles);

        return map;
    }

    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //取消之前的分配
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, assginRoleVo.getUserId());
        sysUserRoleService.remove(queryWrapper);

        //重新分配
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        for (Long roleId : roleIdList) {
            if (StringUtils.isEmpty(roleId)){
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);

            sysUserRoleService.save(sysUserRole);
        }
    }
}
